from flask import Flask, send_from_directory
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from .config.config import Config
import os
import sys

# 添加src目录到Python路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

# 创建Flask应用实例，指定模板和静态文件目录
app = Flask(__name__, 
            template_folder=Config.TEMPLATE_FOLDER,
            static_folder=Config.STATIC_FOLDER)
app.config.from_object(Config)

# 初始化数据库
db = SQLAlchemy(app)
migrate = Migrate(app, db)

# 初始化模型
from .models.models import define_models
TestCase, TestSuite, TestResult = define_models(db)

# 添加静态文件服务路由
@app.route('/screenshots/<path:filename>')
def screenshots(filename):
    return send_from_directory(Config.SCREENSHOTS_FOLDER, filename)

# 添加favicon路由
@app.route('/favicon.ico')
def favicon():
    return send_from_directory(Config.STATIC_FOLDER, 'favicon.ico', mimetype='image/vnd.microsoft.icon')

# 导入路由（放在db初始化之后避免循环导入）
from .routes.routes import *

if __name__ == '__main__':
    # 创建数据库表
    with app.app_context():
        try:
            db.create_all()
            print("数据库表创建成功")
        except Exception as e:
            print(f"数据库初始化失败: {e}")
    
    # 运行应用
    app.run(debug=True)